<template>
  <div id="product-detail">
    <detail-nav-bar ref="detail-nav" @titleClick="titleClick" />
    <scroll class="scroll-area" 
            ref="scroll"
            :probeType="3"
            @scroll="contentScroll">
      <detail-swiper :topImages="topImages" />
      <detail-base-info :goods="goods"></detail-base-info>
      <detail-shop-info :shop="shop"></detail-shop-info>
      <detail-image-info :image-info="imageInfo" @detailImgLoad="detailImgLoad" />
      <detail-param-info ref="params" :param-info="paramInfo" />
      <detail-comment-info ref="comment" :comment-info="commentInfo" />
      <goods-list ref="recommend" :goods="recommendList" />
    </scroll>
    <back-top @click.native="backClick" v-show="isShowBackTop" />
    <detail-bottom-bar @addCart="addToCart" />
  </div>
</template>

<script>
import Scroll from 'components/common/scroll/Scroll';
import GoodsList from 'components/content/goods/GoodsList';

import DetailNavBar from './childComps/DetailNavBar';
import DetailSwiper from './childComps/DetailSwiper';
import DetailBaseInfo from './childComps/DetailBaseInfo';
import DetailShopInfo from './childComps/DetailShopInfo';
import DetailImageInfo from './childComps/DetailImageInfo';
import DetailParamInfo from './childComps/DetailParamInfo';
import DetailCommentInfo from './childComps/DetailCommentInfo';
import DetailBottomBar from './childComps/DetailBottomBar';

import {getDetail, getRecommendList, Goods, Shop, GoodsParams} from 'network/detail';
import {imgListenerMixin, backTopListenerMixin} from "common/mixin";
import {debounce} from "common/utils";
import {mapActions} from "vuex";

import {Toast} from "vant";

export default {
  name: "Detail",
  components: {
    Scroll,
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    DetailImageInfo,
    DetailParamInfo,
    DetailCommentInfo,
    GoodsList,
    DetailBottomBar
  },
  data() {
    return {
      iid: null,
      topImages: [],
      goods: {},
      shop: {},
      imageInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommendList: [],
      topYList: [],
      getTopYFunc: null,
      currentIndex: 0
    }
  },
  mixins: [imgListenerMixin, backTopListenerMixin],
  beforeCreate() {
    // 进入详情页隐藏tabbar
    this.$store.commit("setTabBarShow", false);
  },
  created() {
    // 1.保存传入的iid
    this.iid = this.$route.params.iid;

    // 2.获取详细数据
    this.getDetail();

    // 3.获取推荐数据
    this.getRecommendList();

    // 4.给getTopYFunc赋值
    this.getTopYFunc = debounce(() => {
      console.log("获取title对应offsetTop的值");
      this.topYList = [];
      this.topYList.push(0);
      this.topYList.push(this.$refs.params.$el.offsetTop);
      this.topYList.push(this.$refs.comment.$el.offsetTop);
      this.topYList.push(this.$refs.recommend.$el.offsetTop);
      this.topYList.push(Number.MAX_VALUE);
      console.log("offsetTopList: ", this.topYList);
    }, 100);
  },
  // 路由离开之前恢复tabbar
  beforeRouteLeave(to, from, next) {
    this.$store.commit("setTabBarShow", true);
    next();
  },
  destroyed() {
    this.$bus.$off('imageLoad', this.imgListener);
  },
  methods: {
    ...mapActions(['saveCartData']),
    // 详情页图片加载完成, 重新计算scrollerHeight可滚动区域的高度, 以及title对应商品信息的offsetTop
    detailImgLoad() {
      this.newRefresh();
      this.getTopYFunc();
    },
    // 点击详情页title, 滚动到对应位置
    titleClick(index) {
      console.log("title index: ", index);
      this.$refs.scroll.scrollTo(0, -this.topYList[index], 100);
    },
    contentScroll(position) {
      // 1.获取positionY的值
      const positionY = -position.y;
      // 2.和topYList中的值进行对比
      /*
      方法一:
      topYList = [0, 10361, 11737, 12004]
      如果 positionY 在0 - 10361之间 index = 0
      如果 positionY 在10361 - 11737之间 index = 1
      如果 positionY 在11737 - 12004之间 index = 2
      如果 positionY 大于或等于12004 index = 3
      */

      /*
      let list = this.topYList;
      for(let i = 0; i < this.topYList.length; i++) {
        if(this.currentIndex === i) {
          continue;
        }
        if((i < list.length - 1 && positionY >= list[i] && positionY < list[i+1]) || (i === list.length - 1 && positionY >= list[i])) {
          this.currentIndex = i;
          console.log("currentIndex: ", i);
          this.$refs['detail-nav'].currentIndex = this.currentIndex;
        }
      }
      */

      /*
      方法二:
      topYList = [0, 10361, 11737, 12004, Number.MAX_VALUE]
      如果 positionY 在0 - 10361之间 index = 0
      如果 positionY 在10361 - 11737之间 index = 1
      如果 positionY 在11737 - 12004之间 index = 2
      如果 positionY 在12004 - Number.MAX_VALUE之间 index = 3
      */
      for(let i = 0; i < this.topYList.length - 1; i++) {
        if(this.currentIndex === i) {
          continue;
        }
        if(positionY >= this.topYList[i] && positionY < this.topYList[i + 1]) {
          this.currentIndex = i;
          console.log("currentIndex: ", i);
          this.$refs['detail-nav'].currentIndex = this.currentIndex;
        }
      }

      // 判断BackTop是否显示
      this.backTopListener(position);
    },
    // 添加购物车
    addToCart() {
      console.log("添加购物车, 商品iid: ", this.iid);
      // 1.获取需要在购物车页面展示的商品信息
      const product = {
        image: this.topImages[0],
        title: this.goods.title,
        desc: this.goods.desc,
        price: this.goods.lowNowPrice,
        iid: this.iid
      };

      // 2.将商品信息添加到购物车
      /*
      this.$store.dispatch('saveCartData', product).then(res => {
        Toast({
          type: "success",
          message: res,
          forbidClick: true,
          duration: 500
        });
      });
      */
      this.saveCartData(product).then(res => {
        Toast({
          type: "success",
          message: res,
          // 弹框时禁止点击
          forbidClick: true,
          duration: 500
        });
      });
    },
    // 根据iid请求详情数据
    getDetail() {
      getDetail(this.iid).then(res => {
        console.log("商品详情数据: ", res);
        const data = res.result;

        // 获取轮播图数据
        this.topImages = data.itemInfo.topImages;

        // 获取商品数据
        this.goods = new Goods(data.itemInfo, data.columns, data.shopInfo.services);

        // 获取店铺数据
        this.shop = new Shop(data.shopInfo);

        // 获取图片数据
        this.imageInfo = data.detailInfo;

        // 获取尺寸数据
        this.paramInfo = new GoodsParams(data.itemParams.info, data.itemParams.rule || {});

        // 获取评论数据
        if(data.rate.cRate !== 0) {
          this.commentInfo = data.rate.list[0] || {};
        }

        // 根据最新的数据, 对应的DOM已经被渲染出来了
        // 但是图片可能没有加载完(目前获取到的offsetTop可能不正确)
        // 所以应该在图片加载完成之后获取offsetTop的值
        /*
        this.$nextTick(() => {
          this.topYList = [];
          this.topYList.push(0);
          this.topYList.push(this.$refs.params.$el.offsetTop);
          this.topYList.push(this.$refs.comment.$el.offsetTop);
          this.topYList.push(this.$refs.recommend.$el.offsetTop);
        });
        */
      });
    },
    // 请求推荐数据
    getRecommendList() {
      getRecommendList().then(res => {
        console.log("推荐数据: ", res);
        this.recommendList = res.data.list;
      });
    }
  }
}
</script>

<style scoped>
  #product-detail {
    position: relative;
    height: 100vh;
  }

  .scroll-area {
    position: absolute;
    left: 0;
    right: 0;
    top: 44px;
    bottom: 49px;
    overflow: hidden;
  }
</style>